<!-- 职位管理新增组件 -->
<template>
  <a-drawer
    :width="600"
    v-model:visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    unmountOnClose
  >
    <template #title> 新增职位 </template>
    <div>
      <a-form :model="formData" ref="refForm" :rules="rules" auto-label-width>
        <a-form-item label="标准职位名称：" field="name">
          <a-input placeholder="请输入" v-model="formData.name"></a-input>
        </a-form-item>
        <a-form-item label="标准职位编码：" field="positionCode">
          <a-input
            placeholder="系统自动生成"
            disabled
            v-model="formData.positionCode"
          ></a-input>
        </a-form-item>
        <!-- <a-form-item label="关联职务：" field="relatedId">
          <a-select v-model="formData.relatedId" placeholder="请选择">
            <a-option v-for="item in jobList" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="职位类别：" field="positionTypeId">
          <a-tree-select
            v-model="formData.positionTypeId"
            :fieldNames="{
              key: 'id',
              title: 'name'
            }"
            :data="positionTypeList"
            placeholder="请选择"
            :allow-search="true"
            allow-clear
            :filter-tree-node="filterPositionType"
            @change="positionTypeChange(formData.positionTypeId)"
            @clear="clearType"
            ref="positionTypeRef"
          ></a-tree-select>
        </a-form-item>
        <!-- <a-form-item label="职位序列：" field="">
          <a-select v-model="formData.positionSequenceId" placeholder="请选择">
            <a-option></a-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="选择职位说明书模板：" field="templateId">
          <template #label>
            <span
              >选择职位说明书模板：
              <a-tooltip
                content="注意：如果先选择了职位类别，则优先使用对应职位类别里面的模板。否则优先使用职位说明书的模板！"
              >
                <icon-exclamation-circle-fill style="color: #165dff" />
              </a-tooltip>
            </span>
          </template>
          <a-select v-model="formData.templateId" placeholder="请选择">
            <a-option
              v-for="item in templateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择人员模板：" field="personnelTemplateId">
          <a-select
            allow-search
            allow-clear
            v-model="formData.personnelTemplateId"
            placeholder="请选择"
          >
            <a-option
              v-for="item in personTemplateList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职位层级：" field="positionLevelId">
          <a-select
            v-model="formData.positionLevelId"
            placeholder="请选择"
            @change="handlePositionLevel"
          >
            <a-option
              v-for="item in positionLevelList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="职级范围：" field="positionRange">
          <a-select
            :disabled="!formData.positionLevelId"
            v-model="formData.positionRange"
            :popup-visible="false"
            @click="openModal"
            placeholder="请选择"
          >
          </a-select>
        </a-form-item>
        <a-form-item label="是否特殊工种：" field="">
          <a-radio-group v-model="formData.isSpecial">
            <a-radio value="是">是</a-radio>
            <a-radio value="否">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="是否关键职位：" field="">
          <a-radio-group v-model="formData.isKey">
            <a-radio value="是">是</a-radio>
            <a-radio value="否">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="职位使命：" field="">
          <a-textarea
            allowClear
            v-model="formData.remark"
            :maxLength="300"
            :autoSize="{
              minRows: 5
            }"
            placeholder="请输入"
            showWordLimit
          ></a-textarea>
        </a-form-item>
        <a-form-item label="是否启用该职位：" field="enable">
          <a-radio-group v-model="formData.enable">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </div>
    <a-modal
      v-model:visible="modalShow"
      @ok="modelOK"
      @cancel="modalShow = false"
    >
      <template #title> 选择职级 </template>
      <div class="radio">
        <a-radio-group v-model="radioShow" style="margin-bottom: 20px">
          <a-radio value="A">单个职级 </a-radio>
          <a-radio value="B">职级范围 </a-radio>
        </a-radio-group>
        <div class="son-radio" v-show="radioShow === 'A'">
          职级({{ positionRangeData[0]?.levelDown }}~{{
            positionRangeData[0]?.levelUp
          }})：
          <a-input-number
            v-model="positionRangeNum.num"
            :min="positionRangeData[0]?.levelDown"
            :max="positionRangeData[0]?.levelUp"
            style="width: 150px"
          />
        </div>
        <div class="son-radio" v-show="radioShow === 'B'">
          <span>
            职级范围({{ positionRangeData[0]?.levelDown }}~{{
              positionRangeData[0]?.levelUp
            }})：</span
          >
          <a-input-number
            v-model="positionRangeNum.min"
            :min="positionRangeData[0]?.levelDown"
            :max="positionRangeData[0]?.levelUp"
            style="width: 150px"
          />
          <span style="margin: 0 10px">—</span>
          <a-input-number
            v-model="positionRangeNum.max"
            :min="positionRangeNum.min"
            :max="positionRangeData[0]?.levelUp"
            style="width: 150px"
          />
        </div>
      </div>
    </a-modal>
  </a-drawer>
</template>

<script lang="ts" setup>
import { controldataTreeFilter } from '@/utils/utils';
import { validateRules } from '@/utils/common';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import {
  GetPositionTypeList,
  GetPositionLevelList
} from '@/apis/management/organization/baseSetting';
import {
  GetPositionTemplate,
  PutPositionTemplateState,
  GetPositionDefaultTemplate,
  GetPositionTypeCodeById
} from '@/apis/management/organization/baseSetting/PositionSystem';
import { GetlistData } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  GetJobList,
  GetPositionStandardDefault,
  CheckPositionStandard
} from '@/apis/management/organization/positionManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import { cloneDeep } from 'lodash';

const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    list?: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['update:visible', 'positionAddEmit']);

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emit('update:visible', visible);
  }
});

// 校验名字查重
const validateName = async (val: string, cb: any) => {
  try {
    const data = {
      name: val
    };
    const res = await validateRules(CheckPositionStandard, data);
    if (res.code) {
      cb(`${res.msg}`);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 校验编码查重
// const validateCode = async (val: string, cb: any) => {
//   try {
//     const data = {
//       name: val
//     };
//     const res = await validateRules(CheckPositionStandard, data);
//     if (res.code) {
//       cb(`${res.data}`);
//     }
//   } catch (error: unknown) {
//     console.log(error);
//   }
// };

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ],
  positionCode: [
    // {
    //   required: true,
    //   message: '请输入'
    // }
  ],
  companyId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionDept: [
    {
      required: true,
      message: '请选择'
    }
  ],
  headcount: [
    {
      required: true,
      message: '请输入'
    }
  ],
  relatedId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionTypeId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  templateId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  personnelTemplateId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionLevelId: [
    {
      required: true,
      message: '请选择'
    }
  ],
  positionRange: [
    {
      required: true,
      message: '请选择'
    }
  ],
  enable: [
    {
      required: true,
      message: '请选择'
    }
  ]
};

let formData = ref<any>({
  name: '', // 职位名称
  positionCode: '', // 职位编码
  companyId: undefined, // 公司id
  positionDept: undefined, // 所属部门
  headcount: undefined, // 编制人数
  relatedId: undefined, // 关联职务
  standJobId: undefined, // 关联标准职位
  positionTypeId: undefined, // 职位类别
  positionType: '', // 职位类别名称
  positionSequenceId: 1, // 职位序列
  templateId: undefined, // 职位模板id
  personnelTemplateId: undefined, // 人员模板id
  positionLevelId: undefined, // 职位层级
  positionRange: undefined, // 职位范围
  isSpecial: '否', // 是否特殊工种 1是 2否
  isKey: '否', // 是否关键职位 1是 2否
  remark: undefined, // 职位使命
  isStand: 2, // 是否标准职位 1是 2否,
  enable: 1 // 是否启用该职位 1是 2否
});
const initData = cloneDeep(formData.value); // 储存初始数据

let positionTypeList = ref<any>([]); // 储存职位类别
let positionLevelList = ref<any>([]); // 储存职位层级
let companyList = ref<any>([]); // 储存公司类型的数据
let personTemplateList = ref<any>([]); // 储存人员模板列表数据

let jobList = ref<any>([]); // 储存职务数据

const getData = async () => {
  try {
    const [
      positionTypeListRes,
      positionLevelListRes,
      jobListRes,
      companyListRes,
      humanTemplateListRes,
      // 获取职位说明书
      templateListRes
    ] = await Promise.all([
      // 获取职位类型
      GetPositionTypeList(),
      // 获取职位层级
      GetPositionLevelList({ pageNumber: 0, pageSize: -1 }),
      // 获取职务管理数据
      GetJobList({ pageNumber: 0, pageSize: -1 }),
      // 获取公司
      GetlistData({ type: 1 }),
      // 获取人员模板列表
      GetHumanTemplateList({ pageNumber: 0, pageSize: -1 }),
      GetPositionTemplate({
        pageNumber: 0,
        pageSize: -1,
        ownerType: 4
      })
    ]);
    positionTypeList.value = dealTreeData(
      positionTypeListRes.positionCategoryList
    ).filter((item: any) => item.isEnable === 1); // 启用状态下的职位类型才能选择

    positionLevelList.value = positionLevelListRes.content;
    jobList.value = jobListRes.content.filter(
      (item: any) => item.postStatus === 1
    ); // 启用状态才能选择
    companyList.value = companyListRes.filter((item: any) => item.enable === 1); // 启用状态下的组织才能被选择
    personTemplateList.value = humanTemplateListRes.content.filter(
      (item: any) => item.enable === 1
    );
    templateList.value = templateListRes.content.filter(
      (el: any) => el.enable === 1
    );
  } catch (error: unknown) {
    console.log(error);
  }
};

watch(modalVisible, (newVal: boolean, oldVal: boolean) => {
  if (newVal) getData();
});

// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为叶子节点信息)
const dealTreeData = (treeData: any) => {
  const data = treeData.map((item: any) => ({
    ...item,
    // ...controldataTreeFilter(item.controlData),
    // 新增叶子节点字段
    isLeaf: item.children ? false : true,
    // 新增是否能被选中字段，默认只能选叶子
    selectable: item.children ? false : true,
    // 如果children为空数组，则置为null
    children:
      item.children && item.children.length ? dealTreeData(item.children) : null
  }));
  return data;
};

// 模糊搜索职位类型
const filterPositionType = (searchValue: string, nodeData: any) => {
  return nodeData.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
};

const templateList = ref([]); // 储存当前模板列表数据

let positionTypeRef = ref();

// 选择职位类型事件
const positionTypeChange = async (ownerId: number) => {
  try {
    if (!formData.value.templateId) {
      nextTick(async () => {
        console.dir(positionTypeRef.value);

        formData.value.positionType =
          positionTypeRef.value.selectedValue[0].label;
        formData.value.templateId = undefined;
        formData.value.positionTypeCode = await fetchPositionCode(
          ownerId as number
        );
        templateList.value = await fetchPositionTemplate(ownerId as number, 2);
        formData.value.templateId = findDefaultTemplateId();
      });
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 清除职位类别
const clearType = async () => {
  try {
    formData.value.templateId = undefined;
    templateList.value = await fetchPositionTemplate(null, 4);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 获取职位模板
const fetchPositionTemplate = async (
  ownerId: number | null,
  ownerType: 2 | 4
) => {
  const { content } = await GetPositionTemplate({
    pageNumber: 0,
    pageSize: -1,
    ownerId,
    ownerType
  });
  return content.filter((item: any) => item.enable === 1);
};

// 获取默认模板
const findDefaultTemplateId = () => {
  const defaultTemplate = templateList.value.find(
    (item: any) => item.isShowDefault === 1
  );
  return defaultTemplate?.id;
};

// 根据职位类别id查找职位类别编码
const fetchPositionCode = async (id: number) => {
  return await GetPositionTypeCodeById({ id });
};

// 选择职位层级
const handlePositionLevel = () => {
  // 每次选择其他的层级清空范围的数据
  formData.value.positionRange = undefined;
};

let modalShow = ref(false);
const radioShow = ref('A');
const positionRangeData = ref<any>([]); // 储存职位范围数据
// 存储职位范围弹窗数据
const positionRangeNum = reactive({
  num: 0,
  min: 0,
  max: 0
});

// 打开职级范围的弹出框
const openModal = () => {
  if (formData.value.positionLevelId) {
    modalShow.value = true;
    positionRangeNum.min = positionRangeData[0].levelDown;
    positionRangeNum.max = positionRangeData[0].levelUp;
    positionRangeNum.num = positionRangeData[0].levelDown;
  }
};
const modelOK = () => {
  // modalShow.value = false;
  if (positionRangeNum.num) {
    formData.value.positionRange = `${positionRangeNum.num}`;
  } else {
    formData.value.positionRange = `${positionRangeNum.min}~${positionRangeNum.max}`;
  }
};
watch(
  () => formData.value.positionLevelId,
  () => {
    positionRangeData.value = positionLevelList.value.filter(
      (ele: any) => ele.id === formData.value.positionLevelId
    );
    console.log(positionRangeData.value, positionLevelList.value);
  }
);
watch(
  () => radioShow.value,
  () => {
    if (radioShow.value === 'A') {
      positionRangeNum.min = 0;
      positionRangeNum.max = 0;
    } else {
      positionRangeNum.num = 0;
    }
  }
);

let refForm = ref(); // 储存表单的ref
// 保存
const handleOk = async () => {
  if (await refForm.value.validate()) {
    modalVisible.value = true;
    return;
  }
  emit('positionAddEmit', formData.value);
  formData.value = cloneDeep(initData);
  modalVisible.value = false;
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
  formData.value = cloneDeep(initData);
};
</script>

<style scoped lang="less"></style>
